<template>
  <div class="future-price-mini-chart">
    <div class="chart-container" ref="chartContainer"></div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, watch, nextTick } from 'vue'
import * as echarts from 'echarts'
import type { FuturePrediction } from '@/types/bulletPrice'

// Props
const props = defineProps<{
  currentPrice: number
  futurePredictions: Record<number, FuturePrediction>
}>()

// 响应式数据
const chartContainer = ref<HTMLElement>()
let chartInstance: echarts.ECharts | null = null

// 初始化图表
const initChart = () => {
  if (!chartContainer.value) return

  chartInstance = echarts.init(chartContainer.value)
  updateChart()

  // 监听窗口大小变化
  window.addEventListener('resize', handleResize)
}

// 处理窗口大小变化
const handleResize = () => {
  if (chartInstance) {
    chartInstance.resize()
  }
}

// 准备图表数据
const prepareChartData = () => {
  // 检查数据是否存在
  if (!props.futurePredictions || typeof props.futurePredictions !== 'object') {
    return { dates: [], prices: [], isUpward: true }
  }

  const predictions = Object.values(props.futurePredictions)
  if (predictions.length === 0) return { dates: [], prices: [], isUpward: true }

  // 添加当前价格作为起点
  const dates = ['现在']
  const prices = [props.currentPrice]

  // 按天数排序并添加预测数据
  predictions
    .sort((a, b) => a.days - b.days)
    .forEach(prediction => {
      dates.push(`${prediction.days}天`)
      prices.push(prediction.price)
    })

  // 判断整体趋势
  const finalPrice = prices[prices.length - 1]
  const isUpward = finalPrice >= props.currentPrice

  return { dates, prices, isUpward }
}

// 更新图表
const updateChart = () => {
  if (!chartInstance) return

  const { dates, prices, isUpward } = prepareChartData()
  
  if (prices.length === 0) return

  // 计算价格范围
  const minPrice = Math.min(...prices)
  const maxPrice = Math.max(...prices)
  const priceRange = maxPrice - minPrice
  const padding = priceRange * 0.1

  // 趋势颜色：上涨红色，下降绿色
  const trendColor = isUpward ? '#d03050' : '#18a058'
  const areaColor = isUpward
    ? ['rgba(208, 48, 80, 0.3)', 'rgba(208, 48, 80, 0.05)']
    : ['rgba(24, 160, 88, 0.3)', 'rgba(24, 160, 88, 0.05)']

  const option = {
    grid: {
      left: 25,
      right: 8,
      top: 5,
      bottom: 15,
      containLabel: false
    },
    xAxis: {
      type: 'category',
      data: dates,
      show: true,
      axisLine: {
        show: false
      },
      axisTick: {
        show: false
      },
      axisLabel: {
        show: true,
        fontSize: 8,
        color: '#666',
        interval: 0, // 显示所有标签，因为未来预测数据较少
        rotate: 0
      }
    },
    yAxis: {
      type: 'value',
      min: priceRange > 0 ? minPrice - padding : minPrice * 0.95,
      max: priceRange > 0 ? maxPrice + padding : maxPrice * 1.05,
      show: true,
      axisLine: {
        show: false
      },
      axisTick: {
        show: false
      },
      axisLabel: {
        show: true,
        fontSize: 8,
        color: '#666',
        formatter: (value: number) => {
          if (value >= 1000) {
            return (value / 1000).toFixed(1) + 'k'
          }
          return value.toFixed(0)
        }
      },
      splitLine: {
        show: true,
        lineStyle: {
          color: '#f0f0f0',
          width: 0.5,
          type: 'dashed'
        }
      },
      splitNumber: 3 // 限制分割线数量
    },
    series: [
      {
        type: 'line',
        data: prices,
        smooth: true,
        symbol: 'circle',
        symbolSize: 3,
        showSymbol: true,
        lineStyle: {
          color: trendColor,
          width: 1.5
        },
        itemStyle: {
          color: trendColor,
          borderWidth: 1,
          borderColor: '#fff'
        },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: areaColor[0] },
            { offset: 1, color: areaColor[1] }
          ])
        },
        emphasis: {
          focus: 'series',
          itemStyle: {
            symbolSize: 5,
            shadowBlur: 8,
            shadowColor: trendColor
          }
        }
      }
    ],
    tooltip: {
      trigger: 'axis',
      formatter: (params: any) => {
        const data = params[0]
        const price = data.value.toLocaleString()
        return `${data.name}<br/>${price} 哈夫币`
      },
      backgroundColor: 'rgba(50, 50, 50, 0.95)',
      borderColor: trendColor,
      borderWidth: 1,
      textStyle: {
        color: '#fff',
        fontSize: 9
      },
      padding: [4, 6],
      extraCssText: 'border-radius: 4px; box-shadow: 0 2px 8px rgba(0,0,0,0.2);'
    },
    animation: true,
    animationDuration: 800,
    animationEasing: 'cubicOut' as const
  }

  chartInstance.setOption(option, true)
}

// 监听数据变化
watch(
  () => [props.currentPrice, props.futurePredictions],
  () => {
    nextTick(() => {
      updateChart()
    })
  },
  { deep: true }
)

// 组件挂载
onMounted(() => {
  nextTick(() => {
    initChart()
  })
})

// 组件卸载
onUnmounted(() => {
  if (chartInstance) {
    chartInstance.dispose()
    chartInstance = null
  }
  window.removeEventListener('resize', handleResize)
})
</script>

<style scoped>
.future-price-mini-chart {
  width: 100%;
  height: 80px;
  margin-top: 4px;
}

.chart-container {
  width: 100%;
  height: 100%;
  border-radius: 3px;
  background: var(--n-card-color);
  border: 1px solid var(--n-border-color);
}

/* 移动端优化 */
@media (max-width: 480px) {
  .future-price-mini-chart {
    height: 70px;
  }
}
</style>
